﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Specialized;
using System.Web;
using MFTool;

namespace UIBase
{
    public class SqlHelperWithAuth : SqlHelper
    {
        public SqlHelperWithAuth()
        {

        }

        public SqlHelperWithAuth(string connName)
            :base(connName)
        {

        }

        protected override void BeforeExcuteSql(ref string sql, ref QueryBulider qb)
        {
            string pathAndQuery = HttpContext.Current.Request.UrlReferrer.PathAndQuery;
            int indexOfFirst = pathAndQuery.IndexOf("&");
            if(indexOfFirst != -1)
            {
                pathAndQuery = pathAndQuery.Substring(0, indexOfFirst);
            }

            string funcSql = "select * from MF_Func where Url = '{0}'".ReplaceArg(pathAndQuery);

            string strSqlConnnect = System.Configuration.ConfigurationManager.ConnectionStrings[EnumConn.MF_Base.ToString()].ToString();
            SqlDataAdapter da = new SqlDataAdapter(funcSql, strSqlConnnect);
            DataTable dt = new DataTable();
            da.Fill(dt);

            if(dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];

                if (dr["DataAuthority"] != null && !string.IsNullOrEmpty(dr["DataAuthority"].ToString()))
                {
                    var dic = dr["DataAuthority"].ToString().JsonToDictionary();
                    if (!string.IsNullOrEmpty(dic.GetValue("SQL")))
                    {
                        string authSql = dic.GetValue("SQL").ReplaceBraceContent(CommonHelper.GetCurrentValueDic());
                        sql = "select * from ({0}) tmpppptttWithAuth where {1}".ReplaceArg(sql, authSql);                        
                    }

                    if (!string.IsNullOrEmpty(dic.GetValue("fieldGrid")))
                    {
                        if (qb == null) qb = new QueryBulider();

                        if (qb.QueryItems == null)
                            qb.QueryItems = new List<QueryItem>();

                        var dicList = dic.GetValue("fieldGrid").JsonToDictionaryList();
                        var currentValueDic = CommonHelper.GetCurrentValueDic();
                        foreach (var fieldGridDic in dicList)
                        {
                            QueryItem qi = new QueryItem();
                            fieldGridDic.SetValue("FieldValue", currentValueDic.GetValue(fieldGridDic.GetValue("FieldValue")));
                            ConvertHelper.UpdateEntity(qi, fieldGridDic);
                            qb.QueryItems.Add(qi);
                        }
                    }
                }
            }
        }
    }
}
